package cn.turboinfo.fuyang.api.domain.admin.usecase.custom;

import cn.turboinfo.fuyang.api.domain.common.service.custom.ServiceCustomService;
import cn.turboinfo.fuyang.api.domain.common.service.staff.HousekeepingStaffService;
import cn.turboinfo.fuyang.api.domain.common.usecase.AbstractUseCase;
import cn.turboinfo.fuyang.api.entity.common.enumeration.custom.ServiceCustomStatus;
import cn.turboinfo.fuyang.api.entity.common.exception.order.ServiceOrderException;
import cn.turboinfo.fuyang.api.entity.common.pojo.custom.ServiceCustom;
import cn.turboinfo.fuyang.api.entity.common.pojo.staff.HousekeepingStaff;
import lombok.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

@Slf4j
@RequiredArgsConstructor
@Component
public class ServiceCustomDetailUseCase extends AbstractUseCase<ServiceCustomDetailUseCase.InputData, ServiceCustomDetailUseCase.OutputData> {

    private final ServiceCustomService serviceCustomService;

    private final HousekeepingStaffService housekeepingStaffService;

    @Override
    protected OutputData doAction(InputData inputData) {

        val serviceOrderOptional = serviceCustomService.getById(inputData.id);
        if (serviceOrderOptional.isPresent()) {
            val serviceOrder = serviceOrderOptional.get();
            val hasPermission = serviceOrder.getCustomStatus() == ServiceCustomStatus.INIT || serviceOrder.getCustomStatus() == ServiceCustomStatus.CANCELLED_BY_COMPANY || serviceOrder.getCustomStatus() == ServiceCustomStatus.CANCELLED_BY_STAFF;
            if (inputData.companyId != null && !inputData.companyId.equals(serviceOrder.getCompanyId()) && !hasPermission) {
                throw new ServiceOrderException("没有查看权限");
            }

            val staff = housekeepingStaffService.getById(serviceOrder.getStaffId()).orElse(new HousekeepingStaff());

            serviceOrder.setStaffName(staff.getName());

            return OutputData.builder()
                    .serviceOrder(serviceOrder)
                    .build();
        }

        return OutputData.builder()
                .serviceOrder(null)
                .build();
    }

    @Getter
    @Setter
    @Builder
    @AllArgsConstructor
    @NoArgsConstructor
    public static class InputData extends AbstractUseCase.InputData {
        private Long id;

        private Long companyId;
    }

    @Getter
    @Setter
    @Builder
    public static class OutputData extends AbstractUseCase.OutputData {
        private ServiceCustom serviceOrder;
    }
}
